//
//  RecodeViewController.m
//  Gegeda_music_MY
//
//  Created by lanou3g on 15/11/3.
//  Copyright © 2015年 周莹. All rights reserved.
//

#import "RecodeViewController.h"
#import "SearchViewController.h"
@interface RecodeViewController ()

@end

@implementation RecodeViewController

- (void)viewDidLoad {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backDidClicked)];
    
    self.navigationItem.rightBarButtonItem.enabled = YES;
    [super viewDidLoad];
 //NSOrderedAscending判断两对象值的大小(按字母顺序进行比较
    if ([[[UIDevice  currentDevice]systemVersion] compare:@"7.0"] != NSOrderedAscending) {
        //7.0第一次运行会提示，是否允许使用麦克风
        AVAudioSession  *session = [AVAudioSession   sharedInstance];
        NSError  *sessionError;
     //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        

          [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (session == nil) {
            NSLog(@"Error creating session: %@",[sessionError   description]);
        }else{
        
        
            [session  setActive:YES error:nil];
        
        }
        
        
        
    }
    
    //存入沙盒
    NSString *doDit = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    self.playName = [NSString  stringWithFormat:@"%@/play.aac",doDit];
    
    //录音设置
    
    self.recoerdSettingsDIt = [[NSDictionary  alloc]initWithObjectsAndKeys: [NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,
    [NSNumber numberWithInt:1000.0],AVSampleRateKey,
    [NSNumber numberWithInt:2],AVNumberOfChannelsKey,
    [NSNumber numberWithInt:8],AVLinearPCMBitDepthKey,
    [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
    [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
    nil];
    //音量图片数组
    self.volumMages = [[NSMutableArray  alloc]initWithObjects:@"RecordingSignal001",@"RecordingSignal002",@"RecordingSignal003",
    @"RecordingSignal004", @"RecordingSignal005",@"RecordingSignal006",
    @"RecordingSignal007",@"RecordingSignal008",   nil];
    
    
    
}
-(void)backDidClicked{
    
    [self.navigationController  popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];

    
}

- (IBAction)downAction:(id)sender {

    
    //按下录音
    if ([self cenRecor]) {
        
        NSError *error = nil;
        //必须真机上测试,模拟器上可能会崩溃
        _recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:_playName] settings:_recoerdSettingsDIt error:&error];
        
        if (_recorder) {
            _recorder.meteringEnabled = YES;
            [_recorder prepareToRecord];
            [_recorder record];
            
            //启动定时器
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(levelTimer:) userInfo:nil repeats:YES];
            
        } else
        {
            int errorCode = CFSwapInt32HostToBig ([error code]);
            NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);
            
        }
    }

    
    
    
    
    
}

-(void)levelTimer:(NSTimer*)timer_
{
    //call to refresh meter values刷新平均和峰值功率,此计数是以对数刻度计量的,-160表示完全安静，0表示最大输入值
    [_recorder updateMeters];
    const double ALPHA = 0.05;
    double peakPowerForChannel = pow(10, (0.05 * [_recorder peakPowerForChannel:0]));
    _lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) *   _lowPassResults;
    
    NSLog(@"Average input: %f Peak input: %f Low pass results: %f", [_recorder averagePowerForChannel:0], [_recorder peakPowerForChannel:0],  _lowPassResults);
    
    if (  _lowPassResults>=0.8) {
       _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:7]];
    }else if(  _lowPassResults>=0.7){
          _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:6]];
    }else if(  _lowPassResults>=0.6){
        _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:5]];
    }else if(  _lowPassResults>=0.5){
      _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:4]];
    }else if(  _lowPassResults>=0.4){
           _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:3]];
    }else if(  _lowPassResults>=0.3){
    _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:2]];
    }else if(  _lowPassResults>=0.2){
        _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:1]];
    }else if(  _lowPassResults>=0.1){
      _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:0]];
    }else{
          _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:0]];
    }
    
}


- (IBAction)upAction:(id)sender {
    
    
    
    
    
    //松开 结束录音
    
    //录音停止
    [_recorder stop];
    _recorder = nil;
    //结束定时器
    [_timer invalidate];
    _timer = nil;
    //图片重置
   _SoundLodeIMage.image = [UIImage imageNamed:[_volumMages objectAtIndex:0]];
}

- (IBAction)playAction:(id)sender {
    NSError *playerError;
    
    //播放
  _play = nil;
  _play= [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:_playName] error:&playerError];
    
    if (     _play == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }else{
        [     _play   play];
    }

    
    
    
}



//判断是否允许使用麦克风7.0新增的方法requestRecordPermission

-(BOOL)cenRecor{
    __block BOOL bCanRecord = YES;
    
    if ([[[UIDevice  currentDevice]systemVersion]compare:@"7.0"]!= NSOrderedAscending) {
        AVAudioSession *audioSesson = [AVAudioSession  sharedInstance];
        
        if ([audioSesson  respondsToSelector:@selector(requestRecordPermission:)]) {
            [AVAudioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                }
                else {
                    bCanRecord = NO;
                    //主线程的弹窗
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        
                        [[[UIAlertView alloc] initWithTitle:nil message:@"app需要访问您的麦克风\n请启用麦克风-设置/隐私/麦克风"  delegate:nil cancelButtonTitle:@"关闭"otherButtonTitles:nil] show];
                        
                        
                    });
                }
            }];

            

            
            }
    }
        
        
        
        
    
        return bCanRecord;





}



@end
